package com.libc.yygh.common.aspect;

import com.libc.yygh.common.DateUtilbc;
import com.libc.yygh.common.LoggerUtil;
import com.libc.yygh.common.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.ProceedingJoinPoint;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

/**
 * *
 *
 * @version 1.0<br>
 * @qualiFild MyDoneTimeAspect.java<br>
 * @author：LiBencheng<br>
 * @date Created on 2021年7月29日<br>
 */
@Aspect
@Component
public class AppMonitorRun
{
    public static Logger log = (Logger) LoggerFactory.getLogger(AppMonitorRun.class);
    String folderName = "methodLogs";

    @Around ("@annotation(monitorCtr)")
    public Object around(ProceedingJoinPoint joinPoint, AppMonitorRuning monitorCtr) throws Throwable
    {
        try
        {
            //当前的时间
            Instant starTime = Instant.now();
            // 这里获取到所有的参数值的数组
            Object[] args = joinPoint.getArgs();
            infoLog("开始調用{[%s]}的方法{[%s]},\r\n参数是：{[%s]}",
                    monitorCtr.funEffect(), monitorCtr.method(), StringUtil.toString(args));
            Object obj = joinPoint.proceed();
            infoLog("{[%s]}的方法{[%s]}结束时间是：{[%s]}一共运行：{[%s ms]}，返回参数【%s】",
                    monitorCtr.funEffect(), monitorCtr.method(), DateUtilbc.currentDateTime(),
                    ChronoUnit.MILLIS.between(starTime, Instant.now()), StringUtil.toString(obj));
            LoggerUtil.getInstance("methodLogs").debug(LoggerUtil.getSplitLine());

            return obj;
        }
        catch (Exception e)
        {
            String msg = String.format("調用{[%s]}程序的方法{[%s]}异常：", monitorCtr.funEffect(), monitorCtr.method());
            log.error("方法調用 --->" + msg);
            System.out.println("方法調用 --->" + msg);
            LoggerUtil.getInstance(folderName).exception(msg, e);
            throw new RuntimeException(e);
        }
    }


    private void infoLog(String msg, Object... objs)
    {
        System.out.println(DateUtilbc.currentDateTime() + "：System.out.println方法調用日志---> "
                                   + String.format(msg, objs));
        log.info("方法調用 --->" + String.format(msg, objs));
        LoggerUtil.getInstance(folderName).debug("方法調用 --->" + String.format(msg, objs));

    }
}
